package com.hamny.chat.client;

import com.google.gwt.appengine.channel.client.Channel;
import com.google.gwt.appengine.channel.client.ChannelError;
import com.google.gwt.appengine.channel.client.ChannelFactoryImpl;
import com.google.gwt.appengine.channel.client.Socket;
import com.google.gwt.appengine.channel.client.SocketListener;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.hamny.chat.client.bean.Token;

public class Chat implements EntryPoint {

	private static final String URL_BASE = GWT.getHostPageBaseURL();

	private String token = null;

	@Override
	public void onModuleLoad() {
		String url = URL_BASE + "get_token";
		// Send request to server and catch any errors.
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

		try {
			Request request = builder.sendRequest(null, new RequestCallback() {
				public void onError(Request request, Throwable exception) {
				}

				public void onResponseReceived(Request request,
						Response response) {
					if (200 == response.getStatusCode()) {
						token = getToken(JsonUtils.<Token> safeEval(response
								.getText()));
					} else {
					}
				}

			});
		} catch (RequestException e) {
		}
	}

	private String getToken(Token token) {
		return token.getToken();
	}

	private void openChannel(String token) {
		Channel channel = ChannelFactory.createChannel(token);
		Socket socket = channel.open(new SocketListener() {
			@Override
			public void onOpen() {
				Window.alert("Channel opened!");
			}

			@Override
			public void onMessage(String message) {
				Window.alert("Received: " + message);
			}

			@Override
			public void onError(ChannelError error) {
				Window.alert("Channel error: " + error.getCode() + " : "
						+ error.getDescription());
			}

			@Override
			public void onClose() {
				Window.alert("Channel closed!");
			}
		});
		socket.close();
	}
}
